<template>
  <div ref="mapRef" class="china-map"></div>
</template>

<script setup>
import * as echarts from 'echarts'
import { feature } from 'topojson-client'
import { onMounted, ref, watch } from 'vue'
import { regionMap } from '@/utils/regionMap'

const props = defineProps({
  scenicList: { type: Array, default: () => [] }
})

const mapRef = ref(null)
let chart

// 1. 省份聚合数据
function getProvinceData(scenicList) {
  if (!Array.isArray(scenicList)) return []
  const provinceData = {}
  scenicList.forEach(spot => {
    const region = regionMap[String(spot.regionId)]
    if (!region) return
    let province = region.province.replace(/(省|市|壮族自治区|回族自治区|维吾尔自治区|自治区|特别行政区)$/, '')
    if (!provinceData[province]) provinceData[province] = []
    provinceData[province].push(spot.scenicAreaName)
  })
  return Object.entries(provinceData).map(([province, spots]) => ({
    name: province,
    value: spots.length,
    spots
  }))
}

// 2. 景区气泡点数据（需有lng/lat）
function getScenicMarks(scenicList) {
  return scenicList
    .filter(spot => typeof spot.lng === 'number' && typeof spot.lat === 'number')
    .map(spot => ({
      name: spot.scenicAreaName,
      value: [spot.lng, spot.lat, 1],
      spotInfo: spot
    }))
}

async function renderMap() {
  if (!mapRef.value) return
  chart = echarts.init(mapRef.value)

  const response = await fetch('https://geojson.cn/api/china/1.6.2/china.topo.json')
  const topoData = await response.json()
  const geoJson = feature(topoData, topoData.objects.default)
  echarts.registerMap('china', geoJson)

  // 省份色块数据
  const allProvinceNames = geoJson.features.map(f => f.properties.name)
  const provinceData = getProvinceData(props.scenicList)
  const provinceDataMap = Object.fromEntries(provinceData.map(item => [item.name, item]))
  const completeProvinceData = allProvinceNames.map(name => {
    if (provinceDataMap[name]) {
      return provinceDataMap[name]
    } else {
      return { name, value: 0, spots: [] }
    }
  })

  // 景区气泡点
  const marks = getScenicMarks(props.scenicList)

  const option = {
tooltip: {
  trigger: 'item',
  formatter(params) {
    // 气泡点
    if (params.seriesType === 'effectScatter') {
      const info = params.data.spotInfo
      return `
        <b>${info.scenicAreaName}</b><br/>
        级别：${info.scenicSpotLevel || '-'}<br/>
        海拔：${info.altitude || '-'}<br/>
        地址：${info.detailAddress || '-'}<br/>
        描述：${info.scenicSpotDescription || '-'}
      `
    }
    // 省份
    if (!params.data) return params.name
    const spots = params.data.spots || []
    if (params.data.value === 0) return `${params.name}<br/>无景区`
    return `${params.name}<br/>景区数量：${spots.length}<br/>` +
      (spots.length ? '景区：<br>' + spots.join('<br>') : '')
  },
  extraCssText: `
    max-width: 320px;
    max-height: 400px;
    overflow-y: auto;
    word-break: break-all;
    white-space: normal;
  `
},
    visualMap: {
      min: 0,
      max: Math.max(...provinceData.map(d => d.value), 1),
      left: 'left',
      top: 'bottom',
      text: ['多','无'],
      inRange: { color: ['#e0e0e0', '#409EFF'] },
      outOfRange: { color: ['#e0e0e0'] },
      calculable: true,
      show: false
    },
    geo: {
      map: 'china',
      roam: true,
      emphasis: { label: { show: true } }
    },
    series: [
      {
        type: 'map',
        map: 'china',
        geoIndex: 0,
        roam: true,
        emphasis: { label: { show: true } },
        data: completeProvinceData
      },
      {
        name: '景区',
        type: 'effectScatter',
        coordinateSystem: 'geo',
        symbolSize: 12,
        showEffectOn: 'render',
        rippleEffect: { brushType: 'stroke' },
        itemStyle: { color: '#ff6f00', shadowBlur: 10, shadowColor: '#333' },
        data: marks,
        zlevel: 2
      }
    ]
  }

  chart.setOption(option)
  window.addEventListener('resize', () => chart && chart.resize())
}

onMounted(renderMap)
watch(() => props.scenicList, () => {
  if (chart) {
    const geoJson = echarts.getMap('china').geoJson
    const allProvinceNames = geoJson.features.map(f => f.properties.name)
    const provinceData = getProvinceData(props.scenicList)
    const provinceDataMap = Object.fromEntries(provinceData.map(item => [item.name, item]))
    const completeProvinceData = allProvinceNames.map(name => {
      if (provinceDataMap[name]) {
        return provinceDataMap[name]
      } else {
        return { name, value: 0, spots: [] }
      }
    })
    const marks = getScenicMarks(props.scenicList)
    console.log('气泡点 marks:', marks);
    chart.setOption({
      series: [
        { data: completeProvinceData },
        { data: marks }
      ]
    })
  }
})
</script>

<style scoped>
.china-map {
  width: 100%;
  height: 800px;
  border: none !important;
}
</style>